package service

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"weibo/basic/config"
	"weibo/handler/model"
	"weibo/handler/request"
	"weibo/pkg"
)

func AddPost(c *gin.Context) {
	var form request.AddPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	if len(form.Content) > 140 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "文本内容不超过140字",
		})
		return
	}
	text := pkg.CheckText(form.Content)
	if text == 2 || text == 3 || text == 4 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "内容不合规",
		})
		return
	}
	post := model.Post{
		UserId:      form.UserId,
		Content:     form.Content,
		PostImage:   form.PostImage,
		TalkContent: form.TalkContent,
	}
	if err := post.AddPost(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "发布微博错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发布微博成功",
	})
	return
}
func GetFriendPost(c *gin.Context) {
	var form request.GetFriendPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	list, err := post.GetFriendPost(config.DB, form.UserId, form.Page, form.Size)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询关注用户微博错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询关注用户微博成功",
		"data": gin.H{
			"list": list,
		},
	})
	return
}

func GetMyPost(c *gin.Context) {
	var form request.GetMyPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	list, err := post.GetMyPost(config.DB, form.UserId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询当前用户微博失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询当前用户微博成功",
		"data": gin.H{
			"list": list,
		},
	})
	return
}
func GetPost(c *gin.Context) {
	var form request.GetPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	err := post.GetPost(config.DB, form.PostId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询微博详情失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询微博详情成功",
		"data": gin.H{
			"post": post,
		},
	})
	return
}

func DelPost(c *gin.Context) {
	var form request.DelPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	err := post.DelPost(config.DB, form.PostId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "删除微博失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除微博成功",
	})
	return
}
